﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.Data;
using StyleMVVM.Data.Activation;
using StyleMVVM.DependencyInjection;
using StyleMVVM.Utilities;

namespace StyleMVVM.Configuration
{
	public class AppConfigStorageProvider : IConfigurationStorageProvider, IActivationAware
	{
		public static void RegisterExport(IDependencyInjectionContainer container)
		{
			container.Register(typeof(AppConfigStorageProvider)).
			          As(typeof(IConfigurationStorageProvider));
		}

		public bool CanSet
		{
			get { return false; }
		}

		public Task<ConfigValuePair> GetValue(string valueName, Type valueType)
		{
			string appSettingValue = System.Configuration.ConfigurationManager.AppSettings[valueName];

			bool returnValue = false;
			object returnT = null;

			if (!string.IsNullOrEmpty(appSettingValue))
			{
				if (valueType != typeof(string))
				{
					if (valueType.GetTypeInfo().IsPrimitive)
					{
						returnT = Convert.ChangeType(appSettingValue, valueType);
					}
					else if (valueType.GetTypeInfo().IsEnum)
					{
						returnT = Enum.Parse(valueType, appSettingValue);
					}
					else
					{
						DataContractSerializer serializer =
							new DataContractSerializer(valueType, ReflectionService.KnownTypes);

						using (MemoryStream ms = new MemoryStream())
						{
							using (StreamWriter newStream = new StreamWriter(ms))
							{
								newStream.Write(appSettingValue);
							}

							ms.Position = 0;

							returnT = serializer.ReadObject(ms);
						}
					}
				}
				else
				{
					returnT = appSettingValue;
				}

				returnValue = true;
			}

			return TaskHelper.ReturnTask(new ConfigValuePair { ConfigValue = returnT, ReturnValue = returnValue });
		}

		public Task<bool> SetValue(string valueName, object newValue)
		{
			return TaskHelper.ReturnTask(false);
		}

		public Task<ConfigValuePair> GetUserValue(string username, string valueName, Type valueType)
		{
			return TaskHelper.ReturnTask(new ConfigValuePair { ReturnValue = false });
		}

		public Task<bool> SetUserValue(string username, string valueName, object newValue)
		{
			return TaskHelper.ReturnTask(false);
		}

		public void Activate()
		{
		}
	}
}